﻿using System;
using System.Data;
using MySql.Data.MySqlClient;
using l1cs.server;
using l1cs.server.datatables;
using l1cs.server.utils;

namespace l1cs.server
{
    public class IdFactory
    {
        private Logger _log = Logger.getLogger( typeof( IdFactory ).FullName );

        private int _curId;

        private Object _monitor = new Object();

        private const int FIRST_ID = 0x10000000;

        private static IdFactory _instance = new IdFactory();

        private IdFactory()
        {
            loadState();
        }

        public static IdFactory getInstance()
        {
            return _instance;
        }

        /// <summary>
        /// オブジェクトIDを返す。
        /// </summary>
        /// <returns></returns>
        public int nextId()
        {/*TTOK*/
            lock ( _monitor )
            {
                return _curId++;
            }
        }

        private void loadState()
        {
            // DBからMAXIDを求める
            String sqlstr = "select max(id)+1 as nextid from (" +
                            "          select id            from character_items " +
                            "union all select id            from character_teleport " +
                            "union all select id            from character_warehouse " +
                            "union all select id            from character_elf_warehouse " +
                            "union all select objid as id   from characters " +
                            "union all select clan_id as id from clan_data " +
                            "union all select id            from clan_warehouse " +
                            "union all select objid as id   from pets) t";
            int id = 0;
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                Object obj = wrapper.ExecScaler( sqlstr );
                if ( !( obj is DBNull ) )
                {
                    id = SqlUtils.toInt( obj );
                }
            }

            if ( id < FIRST_ID )
            {
                id = FIRST_ID;
            }
            _curId = id;
            _log.info( "現在のオブジェクトID: " + _curId );
        }
    }
}
